import 'dart:io';

import 'package:audioplayers/audioplayers.dart';
import 'package:ffmpeg_kit_flutter/ffmpeg_kit.dart';
import 'package:ffmpeg_kit_flutter/return_code.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:path_provider/path_provider.dart';
import 'package:proj_sfv/component/LoadingOverlay.dart';
import 'package:proj_sfv/component/MyVideoPlayer.dart';
import 'package:proj_sfv/component/musicPlayer.dart';
import 'package:proj_sfv/domain/Material.dart';
import 'package:proj_sfv/http/api.dart';
import 'package:proj_sfv/http/requests.dart';
import 'package:tencent_cloud_chat_uikit/tencent_cloud_chat_uikit.dart';
import 'package:tencentcloud_cos_sdk_plugin/cos.dart';
import 'package:tencentcloud_cos_sdk_plugin/cos_transfer_manger.dart';
import 'package:tencentcloud_cos_sdk_plugin/pigeon.dart';
import 'package:tencentcloud_cos_sdk_plugin/transfer_task.dart';
import 'package:http/http.dart' as http;
import 'package:uuid/uuid.dart';

class VideoEditPage extends StatefulWidget {
  @override
  _AddMusicPageState createState() => _AddMusicPageState();


  VideoEditPage(this.videoFilePath, this.length);

  String videoFilePath;
  int length;
}

class _AddMusicPageState extends State<VideoEditPage> {
  // 选择的音频素材
  MyMaterial selectedMusic;
  String _selectedMusicUrl;
  // 音频素材列表
  List<MyMaterial> musicList = [];
  // 开始时间
  double startTime = 0;
  // 结束时间
  double endTime = 100.0;
  //
  double audioLength = 100;

  AudioPlayer audioPlayer = AudioPlayer();

  RangeValues selectRange = RangeValues(0, 0);

  bool processing = false;

  @override
  void initState() {
    selectedMusic = MyMaterial.empty();
    _selectedMusicUrl = "";
    endTime = widget.length.toDouble();
    selectRange = RangeValues(0, widget.length.toDouble());
    getAllMaterialsRequest(context).then((value) {
      setState(() {
        musicList = value;
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('为视频添加音乐素材'),
      ),
      body: LoadingOverlay(
        isLoading: processing,
        child: Column(
          children: [
            // 音频素材列表
            Expanded(
              child: ListView.builder(
                itemCount: musicList == null ? 0 : musicList.length,
                itemBuilder: (context, index) {
                  var music = musicList[index];
                  return ListTile(
                    title: Text(music.name),
                    onTap: () async {
                      selectedMusic = music;
                      _selectedMusicUrl = Uri.https(cosHost2, '${selectedMusic.id}.mp3').toString();
                      await audioPlayer.play(UrlSource(_selectedMusicUrl));
                      var duration = await audioPlayer.getDuration();
                      setState(() {
                        audioLength = duration.inSeconds.toDouble();
                      });
                    },
                  );
                },
              ),
            ),
            // 显示添加素材的视频封面
            FutureBuilder(builder: (context, snapshot) {
              return MusicPlayerWidget(audioPlayer, () async {
                await audioPlayer.play(UrlSource(_selectedMusicUrl));
                // audioPlayer.state = PlayerState.playing;
              });
            }),
            Expanded(
              flex: 2,
              child: Container(
                color: Colors.grey,
                child: Center(
                  child: selectedMusic == null
                      ? Text('请从列表中选择音频素材')
                      : Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text('已选择音频素材：${selectedMusic.name}'),
                      SizedBox(height: 20),
                      Text('开始时间：${Duration(seconds: startTime.toInt()).toString().split(".").first}'),
                      SizedBox(height: 10),
                      Slider(
                        value: startTime,
                        min: 0,
                        max: audioLength,
                        onChanged: (value) {
                          setState(() {
                            startTime = value;
                            endTime = startTime + widget.length;
                          });
                        },
                      ),
                      SizedBox(height: 10),
                      Text('结束时间：${Duration(seconds: endTime.toInt()).toString().split(".").first}'),
                      SizedBox(height: 10),
                      Slider(
                        value: endTime,
                        min: 0,
                        max: audioLength,
                        onChanged: (value) {
                          setState(() {
                            endTime = value;
                            startTime = endTime - widget.length;
                          });
                        },
                      ),
                      ElevatedButton(onPressed: () async {
                        setState(() {
                          processing = true;
                        });
                        var resp = await http.get(Uri.parse(_selectedMusicUrl));
                        final tempFolder = await getExternalStorageDirectory();
                        var file = File('${tempFolder.path}/temp.mp3');
                        if (!file.existsSync()) {
                          file = await file.create();
                        }
                        await file.writeAsBytes(resp.bodyBytes);
                        final outFilePath = '${tempFolder.path}/${Uuid().v4()}.mp4';
                        final command = "-i ${widget.videoFilePath} -ss "
                            "${Duration(seconds: startTime.toInt()).toString().split(".").first} -t "
                            "${Duration(seconds: widget.length).toString().split(".").first} -i ${file.path} -c:v copy -c:a aac "
                            "-map 0:v:0 -map 1:a:0 $outFilePath";
                        var session = await FFmpegKit.execute(command);
                        final code = await session.getReturnCode();
                        if (ReturnCode.isSuccess(code)) {
                          file.deleteSync();
                          Navigator.pop(context, outFilePath);
                        } else {
                          setState(() {
                            Fluttertoast.showToast(msg: "未知错误");
                            processing = false;
                          });
                        }
                        // int rc = await _flutterFFmpe
                      }, child: Text("合成"))
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
